import { useRequest } from 'vue-hooks-plus';
import { useMessage } from '@/hooks/useMessage';
import {
  UseRequestOptions,
  UseRequestPlugin,
  UseRequestService,
} from 'vue-hooks-plus/lib/useRequest/types';
import { download } from '@/utils/download';
export function useTablePage<
  TData extends {
    total: number;
    rows: T[];
  },
  TParams extends unknown[] = unknown[],
  PluginsOptions extends UseRequestPlugin<TData, TParams>[] = UseRequestPlugin<
    TData,
    TParams
  >[],
  T = any,
>(config: {
  fileName?: string;
  transformQueryParams?: (query: any) => any;
  queryApi: UseRequestService<TData, TParams>;
  deleteApi?: (...args: any) => Promise<any>;
  exportApi?: (...args: any) => Promise<any>;
  initValue?: any;
  queryConfig?: UseRequestOptions<
    TData,
    TParams,
    PluginsOptions extends (infer P)[]
      ? P extends UseRequestPlugin<TData, TParams, infer R>
        ? R
        : never
      : never
  >;
}) {
  const message = useMessage();
  const pageInfo = {
    pageNum: ref(1), // 当前记录起始索引
    pageSize: ref(10), // 每页显示记录数
  };
  const queryParams = reactive({
    ...pageInfo,
    ...config.initValue,
  });
  const queryFormRef = ref(); // 搜索的表单
  function getFinallyQueryParams(req?: any): any {
    // @ts-ignore
    return (config.transformQueryParams || ((v: any) => v))({
      ...queryParams,
      // @ts-ignore
      ...config.queryConfig?.defaultParams?.[0],
      ...req,
    });
  }
  const req = useRequest(
    (async (req: any) => {
      // @ts-ignore
      return config.queryApi(getFinallyQueryParams()).then(res => {
        return {
          ...res,
          rows: (res.rows || []).map((item, index) => {
            return {
              ...item,
              _index:
                (pageInfo.pageNum.value - 1) * pageInfo.pageSize.value +
                index +
                1,
            };
          }),
        };
      });
    }) as any as UseRequestService<TData, TParams>,

    config.queryConfig
  );
  const { runAsync: getList, data } = req;
  const total = computed(() => {
    return parseInt(data?.value?.total as any) || 0;
  });
  const pagination = reactive({
    'hide-on-single-page': false,
    total,
    'page-size': pageInfo.pageSize,
    'current-page': pageInfo.pageNum,
    layout: 'prev, pager, next, jumper, sizes, ->, total',
    pageSizes: [10, 20, 50, 100, 200],
    onSizeChange(v: number) {
      queryParams.pageSize = v;
      // @ts-ignore
      getList();
    },
    onCurrentChange(v: number) {
      queryParams.pageNum = v;
      // @ts-ignore
      getList();
    },
  });
  const list = computed(() => {
    return data?.value?.rows || [];
  });
  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.pageNum = 1;
    // @ts-ignore
    getList();
  };

  /** 重置按钮操作 */
  const resetQuery = () => {
    queryFormRef.value.resetFields();
    handleQuery();
  };

  /** 删除按钮操作 */
  const handleDelete = async (...args: any) => {
    // 删除的二次确认
    await message.delConfirm();
    if (config.deleteApi) {
      // 发起删除
      await config.deleteApi(...args);
      message.success('删除成功');
      // 刷新列表
      // @ts-ignore
      await getList();
    }
  };
  return {
    queryFormRef,
    handleQuery,
    handleDelete,
    resetQuery,
    ...req,
    list,
    total,
    queryParams,
    pagination,
    getFinallyQueryParams,
    exportHandle(
      config2: { query?: any; fileName?: string } = { fileName: '下载' }
    ) {
      const queryParams = {
        ...getFinallyQueryParams(),
        pageNum: undefined,
        pageSize: undefined,
        ...config2.query,
      };
      return config
        .exportApi?.(
          {
            ...queryParams,
          },
          {
            responseType: 'blob',
          }
        )
        .then(res => {
          return download(res, config2.fileName || config.fileName!);
        });
    },
  };
}
